#include "task.hpp"
#include <iostream>
#include <unistd.h>
#include <cassert>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
class ManPro
{
public:
    ManPro(int fd,pid_t ProPid,std::string ProName)
        :_fd(fd)
        ,_ProPid(ProPid)
        ,_ProName(ProName)
    {}
public:
    int _fd;
    pid_t _ProPid;
    std::string _ProName;
};





void AcceptTask()
{
    //rade(0)
    while(true)
    {
        int num = 0;
        int n = read(0,&num,sizeof(int));
        // std::cout<< n << " num:"<<num<<std::endl;
        if(n == 0) break;
        my_task::task tk;
        tk._VecTask[num]();
        
        //else if(n == 0) break;
    }
    
}


void CrePro(std::vector<ManPro>* manpro,int n)
{
    int pipefd[N] = {0};
    int m = pipe(pipefd);
    assert(!m);
    std::vector<int> oldfd;
    for(int i = 0;i < n;i++)
    {
        pid_t id = fork();
        if(id == 0)
        {
            for(auto& fd : oldfd)
            {
                close(fd);
            }
            close(pipefd[1]);
            dup2(pipefd[0],0);
            close(pipefd[0]);
            
            //接受任务
            AcceptTask();
            exit(0);
        }

        close(pipefd[0]);
        

        //记录子进程信息
        std::string name = "process-" + std::to_string(i);
        manpro->push_back(ManPro(pipefd[1],id,name));
        oldfd.push_back(pipefd[1]);
    }
    
}
void DistriTask(std::vector<ManPro> manpro)
{
    while(true)
    {
        int p = rand() % 10;
        int num = rand() % 4;
        write(manpro[p]._fd,&num,sizeof(int));
        std::cout<<manpro[p]._ProName<<" num:"<<num<<std::endl;
        sleep(1);
    }
}


void Waitpro(std::vector<ManPro>& manpro)
{
    for(auto & fd : manpro)
    {
        close(fd._fd);
        pid_t id = waitpid(fd._fd,nullptr,0);
        if(id == -1)
        {
            perror("waitpid");
        }
    }
}
int main()
{
    std::vector<ManPro> manpro;
    srand((unsigned int)time(nullptr));
    //创建n个进程,建立管道
    int n = 10;
    CrePro(&manpro,n);
    // for(auto& c: manpro)
    // {
    //     std::cout<<"pro:"<<c._ProName<< std::endl;
    // }
    
    
    //向子进程分配任务
    DistriTask(manpro);

    Waitpro(manpro);


    return 0;
}